package com.example.blogsystem.utils;

import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class SecurityUtils {
    /*
    * 加密
    * */
    public static String encrypt(String password) {
        String salt = UUID.randomUUID().toString().replace("-","");
        //mds
        String secretString = null;
        try {
            secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //数据库储存，盐值加密码
        return salt+secretString;
    }
    /*
    * 解密
    * */
    public static Boolean verify(String password,String finalPassword) throws UnsupportedEncodingException {
        if(finalPassword==null || finalPassword.length() != 64) {
            System.out.println("密码长度不足");
            return false;
        }
        String salt = finalPassword.substring(0,32);
        String secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        boolean result = (salt+secretString).equals(finalPassword);
        System.out.println(result);
        return result;
    }
}
